package org.achievement.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.achievement.system.common.RequestResult;
import org.achievement.system.common.annotations.InterfaceAuth;
import org.achievement.system.common.enums.AuthEnum;
import org.achievement.system.common.exception.ServiceException;
import org.achievement.system.dao.RoleDao;
import org.achievement.system.dao.ScoreDao;
import org.achievement.system.dao.UserDao;
import org.achievement.system.pojo.entity.Role;
import org.achievement.system.pojo.entity.User;
import org.achievement.system.pojo.form.LoginForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO: 页面名字不能与接口名相同
 */
@RestController
public class CommonController {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private ScoreDao scoreDao;


    public static void commonSetting(ModelAndView modelAndView) {
        modelAndView.addObject("time", Calendar.getInstance().getTimeInMillis());
    }

    /**
     * 首页
     * @param modelAndView
     * @return
     */
    @InterfaceAuth({AuthEnum.ADMIN, AuthEnum.TEACHER, AuthEnum.STUDENT})
    @RequestMapping("/index")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("index");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 登录页面
     * @return
     */
    @GetMapping("/login")
    public ModelAndView login(ModelAndView modelAndView){
        modelAndView.setViewName("login");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 首页
     * @return
     */
    @GetMapping("/main")
    public ModelAndView mainPage(ModelAndView modelAndView){
        modelAndView.setViewName("main");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 登录请求
     * @param loginForm
     * @return
     */
    @PostMapping("/login")
    public RequestResult login(HttpServletRequest request, @RequestBody LoginForm loginForm) {
        if (loginForm == null ||
                StrUtil.isBlank(loginForm.getUsername()) ||
                StrUtil.isBlank(loginForm.getPassword())) {
            throw new ServiceException("请输入用户名和密码！");
        }
        User user = userDao.selectOne(new QueryWrapper<User>()
                .eq("username", loginForm.getUsername())
                .eq("password", loginForm.getPassword()));
        if (user == null) {
            throw new ServiceException("用户名或密码不正确！");
        }

        // 查询角色
        Role role = roleDao.selectOne(new QueryWrapper<Role>().eq("id", user.getRoleId()));
        if (role == null) {
            throw new ServiceException("请登录管理员账号配置角色！");
        }

        // 登录信息存储到session中
        HttpSession session = request.getSession();
        session.setAttribute("username", user.getUsername());

        return RequestResult.success("登录成功！");
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("/logout")
    public RequestResult logout(HttpServletRequest httpServletRequest) throws ServletException {
        httpServletRequest.getSession().removeAttribute("username");
        httpServletRequest.logout();
        return RequestResult.success("已退出登录，请返回登录页！");
    }

    /**
     * 注册页面
     * @return
     */
    @GetMapping("/register")
    public ModelAndView register(ModelAndView modelAndView){
        modelAndView.setViewName("register");
        commonSetting(modelAndView);
        return modelAndView;
    }

    /**
     * 注册请求
     * @param user
     * @return
     */
    @PostMapping("/register")
    public RequestResult register(@RequestBody User user) {
        if (user == null || StrUtil.isBlank(user.getUsername()) ||
                StrUtil.isBlank(user.getPassword())) {
            throw new ServiceException("用户名或密码不能为空！");
        }

        // 判断是否存在该角色
        QueryWrapper<Role> queryRole = new QueryWrapper<Role>().eq("id", user.getRoleId());
        Role role = roleDao.selectOne(queryRole);
        if (role == null) {
            throw new ServiceException("不存在该角色！");
        }

        if (AuthEnum.ADMIN.getRoleName().equals(role.getName()) ||
                AuthEnum.ADMIN.getRoleName().equals(role.getName())) {
            throw new ServiceException("不能注册管理员或教师！");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("username", user.getUsername());
        Long dbUserCount = userDao.selectCount(queryWrapper);
        if (dbUserCount > 0) {
            throw new ServiceException("用户已存在！");
        }
        int insert = userDao.insert(user);
        if (insert != 1) {
            throw new ServiceException("注册失败，请重试！");
        }
        return RequestResult.success(null);
    }

    /**
     * 首页图表数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/chartData")
    public RequestResult chartData(HttpServletRequest request, HttpServletResponse response) {
        HashMap userCount = userDao.chartData();
        HashMap scoreCount = scoreDao.sumScore();
        HashMap<String, Map> data = new HashMap<>();
        data.put("userCount", userCount);
        data.put("scoreCount", scoreCount);
        return RequestResult.success(data);
    }
}
